package com.aggregate.pay.saobei.support.client;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.saobei.bean.PayNotifyData;
import com.aggregate.pay.saobei.bean.PayNotifyResult;
import com.aggregate.pay.saobei.support.Client;
import com.aggregate.pay.saobei.support.Merch;
import com.aggregate.pay.saobei.support.utils.MD5;

/**
 * 扫呗支付接口-交易通知
 * @author Moyq5
 * @date 2018年6月28日
 */
public class NotifyPay implements Client<PayNotifyData, PayNotifyResult> {
	
	private static final Logger log = LoggerFactory.getLogger(NotifyPay.class);
	
	private Merch merch;
	
	public NotifyPay(Merch merch) {
		this.merch = merch;
	}

	@Override
	public PayNotifyResult execute(PayNotifyData data) {
		// 按固定字段固定顺序组装签名
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("return_code", data.getResultCode());
		map.put("return_msg", data.getReturnMsg());
		map.put("result_code", data.getResultCode());
		map.put("pay_type", data.getPayType());
		map.put("user_id", data.getUserId());
		map.put("merchant_name", data.getMerchantName());
		map.put("merchant_no", data.getMerchantNo());
		map.put("terminal_id", data.getTerminalId());
		map.put("terminal_trace", data.getTerminalTrace());
		map.put("terminal_time", data.getTerminalTime());
		map.put("total_fee", data.getTotalFee());
		map.put("end_time", data.getEndTime());
		map.put("out_trade_no", data.getOutTradeNo());
		map.put("channel_trade_no", data.getChannelTradeNo());
		if (data.getPayType().equals("090")) {
			map.put("receipt_fee", data.getReceiptFee());
		}
		map.put("attach", data.getAttach());
		
		StringBuffer sb = new StringBuffer();
		String value;
		for (Entry<String, Object> entry: map.entrySet()) {
			value = null == entry.getValue() ? "": String.valueOf(entry.getValue());
			sb.append(entry.getKey() + "=" + value + "&");
		}
		sb.append("access_token=" + merch.accessToken());

		log.debug("签名内容：{}", sb.toString());
		String sign = MD5.MD5Encode(sb.toString());
		log.debug("签名值：{}", sign);
		
		if (!data.getKeySign().equalsIgnoreCase(sign)) {
			log.warn("签名失败：源值[{}]!=实际值[{}]", data.getKeySign(), sign);
			PayNotifyResult result = new PayNotifyResult();
			result.setReturnCode("02");
			result.setReturnMsg("签名失败");
			return result;
		}
		
		PayNotifyResult result = new PayNotifyResult();
		result.setReturnCode("01");
		result.setReturnMsg("success");
		return result;
	}
	
}
